package com.clear.subject.domain.util;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 缓存工具类
 */
@Component
public class CacheUtil<K, V> {

    private Cache<String, String> localCache = CacheBuilder.newBuilder()
            .maximumSize(5000)  // 最大缓存项数
            .expireAfterWrite(10, TimeUnit.SECONDS)
            .build();

    /**
     * @param cacheKey 缓存key
     * @param clazz
     * @return
     */
    public List<V> getResult(String cacheKey, Class<V> clazz,
                             Function<String, List<V>> function) {
        List<V> resultList = new LinkedList<>();
        String context = localCache.getIfPresent(cacheKey);

        if (StringUtils.isNotBlank(context)) {
            resultList = JSON.parseArray(context, clazz);
        } else {
            // 本地缓存为空，去查
            resultList = function.apply(cacheKey);
            // 将查询结果写入本地缓存
            if (!CollectionUtils.isEmpty(resultList)) {
                // 查询结果不为空，才写入缓存
                localCache.put(cacheKey, JSON.toJSONString(resultList));
            }
        }
        return resultList;
    }

    public Map<K, V> getMapResult(String cacheKey, Class<V> clazz,
                               Function<String, Map<K, V>> function) {
        return new HashMap<>();
    }
}
